package com.ace.lab.mobile.controller.pays;

import com.ace.lab.base.model.Result;
import com.ace.lab.base.util.ResultBuilder;
import com.ace.lab.pays.dto.BalanceQueryRequestProto;
import com.ace.lab.pays.dto.BalanceQueryResponseProto;
import com.ace.lab.pays.service.AccountServiceGrpc;
import io.grpc.stub.StreamObserver;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

/**
 * Created by ace on 2017/7/6.
 */
@RestController
@RequestMapping("/payment")
public class PayController {

    @Autowired
    private AccountServiceGrpc.AccountServiceStub accountServiceStub;

    @RequestMapping("/balance")
    public Result queryAccountBalance(Long accountId) throws ExecutionException, InterruptedException {
        BalanceQueryRequestProto.BalanceQueryRequest request = BalanceQueryRequestProto.BalanceQueryRequest.newBuilder()
                .setAccountId(accountId)
                .build();
        CompletableFuture<BalanceQueryResponseProto.BalanceQueryResponse> future = new CompletableFuture<>();
        accountServiceStub.queryAccountBalance(request, new StreamObserver<BalanceQueryResponseProto.BalanceQueryResponse>() {
            @Override
            public void onNext(BalanceQueryResponseProto.BalanceQueryResponse value) {
                future.complete(value);
            }

            @Override
            public void onError(Throwable t) {

            }

            @Override
            public void onCompleted() {

            }
        });
        BalanceQueryResponseProto.BalanceQueryResponse response = future.get();
        return new ResultBuilder().data(response).build();
    }
}
